package com.hmall.order.interceptor;

import com.hmall.feign.common.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/*
登录检查拦截器
 */
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1.从request中获取请求头信息
        String admin = request.getHeader("authorization");
        //ThreadLocalUtil.set(admin);
        //return true;
        if ("2".equals(admin)){
            ThreadLocalUtil.set(admin);
            return true;
        }
        log.error("用户未登录,非法访问:{}" , request.getRequestURL());
        //admin为空 ,说明没有登陆,返回未登录的结果
        response.getWriter().print("用户未登录!请先登录!");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    //从线程副本中移除
        ThreadLocalUtil.remove();
    }
}
